﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Csla;
using Csla.Serialization;

namespace Sireass.Bl
{
	[Serializable]
	public class ProgramaList:ReadOnlyListBase<ProgramaList, ProgramaInfo>
	{
		#region Factory
		public static void GetProgramaList(EventHandler<DataPortalResult<ProgramaList>> callback)
		{
			DataPortal.BeginFetch<ProgramaList>(callback);
		}

		public static ProgramaList GetProgramaList()
		{
			return DataPortal.Fetch<ProgramaList>();
		}
		#endregion

		#region Métodos
		public static void AddObjectAuthorizationRules()
		{
			Type type = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType;
			PerfilServicioCriteria criteria = new PerfilServicioCriteria(type.FullName, true);
			PerfilServicioList perfilesPorServicio = PerfilServicioList.GetPerfilServicioList(criteria);
			List<string> roles = new List<string>(perfilesPorServicio.Count);
			foreach (PerfilServicioInfo perfilServicio in perfilesPorServicio)
			{
				roles.Add(perfilServicio.Perfil);
			}
			Csla.Rules.BusinessRules.AddRule(type, new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.GetObject, roles));
		}
		#endregion

		#region Data Portal
		private void DataPortal_Fetch()
		{
			IsReadOnly = false;
			var rlce = RaiseListChangedEvents;
			RaiseListChangedEvents = false;
			using (var dalManager = Sireass.Dal.DalFactory.GetManager())
			{
				var dal = dalManager.GetProvider<Sireass.Dal.IProgramaDal>();
				using (var data = dal.Fetch())
				{
					while (data.Read())
					{
						var item = DataPortal.FetchChild<ProgramaInfo>(data);
						Add(item);
					}
				}
			}
			RaiseListChangedEvents = rlce;
			IsReadOnly = true;
		}
		#endregion
	}
}
